<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta http-equiv="Cache-Control" content="no-siteapp" />
	<meta name="viewport"
		content="width=device-width, maximum-scale=1.0, initial-scale=1.0,initial-scale=1.0,user-scalable=no" />
	<meta name="apple-mobile-web-app-capable" content="yes" />
    <title><#if inviteData?? && inviteData.aititle??>${inviteData.aititle}<#else>智能客服</#if></title>

	<link rel="shortcut icon" type="image/x-icon"
		  href="<#if systemConfig?? && systemConfig.favlogo?? && systemConfig.favlogo != ''>/res/image.html?id=${systemConfig.favlogo?url}<#else>/images/favicon.ico?v=ukefu</#if>&t=${.now?long}" />
    <link rel="stylesheet" type="text/css" href="/im/css/ukefu.css">
    <link rel="stylesheet" id="skin" type="text/css" href="/im/css/default/ukefu.css">
    <!-- kindeditor -->
    <link rel="stylesheet" type="text/css" href="/im/js/kindeditor/themes/default/default.css">
    
    <script src="/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="/im/js/kindeditor/kindeditor.js"></script>
    <script type="text/javascript" src="/im/js/kindeditor/lang/zh-CN.js"></script>
    <script src="/im/js/socket.io.js"></script>
    <script src="/js/recordmp3.js"></script>
    <#if inviteData?? && inviteData.enablevoice?? && inviteData.enablevoice == true>
    <script src="/js/ukefu-voice.js"></script>
    </#if>
    <script src="/js/weixinAudio.js"></script>
    <script src="/js/template.js"></script>
    <script type="text/javascript">
		var editor , words , callback , agent = false , staticagent = false ,schema = '${schema!"http"}' , invite = false , upload = "/im/voice/upload.html?userid=${userid!''}&appid=${appid!''}";
		var tipuser = '<#if inviteData??>${inviteData.tipuser}</#if>' , tipusertitle = '<#if inviteData??>${inviteData.tipusertitle!"您有一条新的消息"}</#if>', tipusericon = '<#if inviteData??>/res/image.html?id=${inviteData.tipusericon!"/images/logo2.png"}</#if>' ;
		var options = {
				transports:[
					<#if inviteData?? && inviteData.transports?? && inviteData.transports =="websocket">
					'websocket'
					<#elseif inviteData?? && inviteData.transports?? && inviteData.transports =="polling" >
					'polling'
					<#else>
					'websocket','polling'
					</#if>
				]
		} ;
		var newmessage = [] , ring = [];
		newmessage['mp3'] = '/images/message.mp3';
		ring['mp3'] = '/images/ring.mp3';
		
        KindEditor.ready(function (K) {
            editor = K.create('textarea[name="content"]', {
                autoHeightMode: false,
                width: "100%",
                resizeType: 0,
                themeType: 'simple',
                fontsize: 16,
				newlineTag : "br" , 
				uploadJson : "/im/image/upload.html?userid=${userid!''}&appid=${appid!''}&orgi=${orgi!''}",
                allowFileManager : false,
                allowInsertUpload:false,		//增加的参数，上传图片后是否插入到当前区域
                allowImageRemote:false,
				filterMode:true,
                items: ['emoticons', 'cut' , 'image'],
				htmlTags: {img : ['src', 'width','data-toggle','data-width','data-height','style', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'] , br:[]}  ,
				afterChange : function() {
					var count = this.count() ;
					var limitNum = <#if inviteData.maxwordsnum gt 0>${inviteData.maxwordsnum}<#else>300</#if>;  //设定限制字数
					var pattern = '还可以输入' + limitNum + '字'; 
					var strValue = this.html();
					if(count > limitNum) {
						pattern = ('字数超过限制，请适当删除部分内容');
						//超过字数限制自动截取			 						
						strValue = strValue.substring(0,limitNum);
						editor.html("");    
						editor.appendHtml(strValue);     
					} else {
						//计算剩余字数
						var result = limitNum - this.count(); 
						pattern = '还可以输入' +  result + '字'; 
						if(result < 20){
							document.getElementById('surplus').style.color = "red" ;	
						}else{
							document.getElementById('surplus').style.color = "#000000" ;								
						}
					}
					
					words = this.count("text") ;
					document.getElementById('surplus').innerHTML = count+"/"+limitNum+" , " + pattern; //输入显示
					 ////////
				},
				afterCreate : function() { //设置编辑器创建后执行的回调函数
					var self = this;
		            <#if inviteData?? && inviteData.ctrlenter?? && inviteData.ctrlenter == true>
			            //Ctrl+Enter提交表单
			            K.ctrl(document, 13, function() {
			                self.sync();
			                sendMessage();
			            });
			            K.ctrl(self.edit.doc, 13, function() {
			                self.sync();
			                sendMessage();
			            });
		            <#else>
						var kindEditorIframe = $("iframe").contents().find("body");  
					    kindEditorIframe.keydown(function (event) {  
						if(event.keyCode==13 && !event.ctrlKey){  
						    self.sync();
							sendMessage();
							return false;
						}else if(event.keyCode==13 && event.ctrlKey){
							editor.insertHtml('<br/>');
						}
					    });  
			    		//Ctrl+Enter提交表单
						K.ctrl(document, 13, function() {
							editor.insertHtml('<br/>');
						});
						K.ctrl(self.edit.doc, 13, function() {
							editor.insertHtml('<br/>');
						});
		            </#if>
		        }
            });
        });
		KindEditor.options.cssData = "body { font-size: 15px; font-family:'Microsoft Yahei', 'Helvetica', 'Simsun', 'Arial';}";
		var R3Ajax = {
			ajax:function(opt){
				var xhr = this.createXhrObject();
				xhr.onreadystatechange = function(){
					if(xhr.readyState!=4) return ;
					(xhr.status===200 ?
						opt.success(xhr.responseText,xhr.responseXML):
						opt.error(xhr.responseText,xhr.status));
				}
				xhr.open(opt.type,opt.url,true);
				if(opt.type!=='post') 
					opt.data=null;
				else
					xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				opt.data = this.parseQuery(opt.data);
				xhr.send(opt.data);
			},
			post:function(url,success,data){
				var popt = {
					url:url,
					type:'post',
					data:data,
					success:success,
					error:function(data){}
				}
				this.ajax(popt);
			},
			get:function(url,success){
				var gopt = {
					url:url,
					type:'get',
					success:success,
					error:function(){}
				}
				this.ajax(gopt);
			},
			createXhrObject:function(){
				var methods = [
					function(){ return new XMLHttpRequest();},
					function(){ return new ActiveXObject('Msxml2.XMLHTTP');},
					function(){ return new ActiveXObject('Microsoft.XMLHTTP');}
				];
				for(var i=0;len=methods.length,i<len;i++){
					try{
						methods[i]();
					}catch(e){
						continue;
					}
					this.createXhrObject = methods[i];
					return methods[i]();
				}
				throw new Error('Could not create an XHR object.');
			},
			parseQuery:function(json){
				if(typeof json == 'object'){
					var str = '';
					for(var i in json){
						str += "&"+i+"="+encodeURIComponent(json[i]);
					}
					return str.length==0 ? str : str.substring(1);
				}else{
					return json;
				}
			},
			audioplayer:function(id, file, loop) {
			    var audioplayer = document.getElementById(id);
			    if (audioplayer != null) {
			        document.body.removeChild(audioplayer);
			    }

			    if (typeof(file) != 'undefined') {
			        if (navigator.userAgent.indexOf("MSIE") > 0) { // IE 
			            var player = document.createElement('bgsound');
			            player.id = id;
			            player.src = file['mp3'];
			            player.setAttribute('autostart', 'true');
			            if (loop) {
			                player.setAttribute('loop', 'infinite');
			            }
			            document.body.appendChild(player);

			        } else { // Other FF Chome Safari Opera 
			            var player = document.createElement('audio');
			            player.id = id;
			            player.setAttribute('autoplay', 'autoplay');
			            if (loop) {
			                player.setAttribute('loop', 'loop');
			            }
			            document.body.appendChild(player);

			            var mp3 = document.createElement('source');
			            mp3.src = file['mp3'];
			            mp3.type = 'audio/mpeg';
			            player.appendChild(mp3);
			        }
			    }
			}
		};
		Date.prototype.format = function(fmt) { 
			 var o = { 
				"M+" : this.getMonth()+1,                 //月份 
				"d+" : this.getDate(),                    //日 
				"h+" : this.getHours(),                   //小时 
				"m+" : this.getMinutes(),                 //分 
				"s+" : this.getSeconds(),                 //秒 
				"q+" : Math.floor((this.getMonth()+3)/3), //季度 
				"S"  : this.getMilliseconds()             //毫秒 
			}; 
			if(/(y+)/.test(fmt)) {
					fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
			}
			 for(var k in o) {
				if(new RegExp("("+ k +")").test(fmt)){
					 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
				 }
			 }
			return fmt; 
		} ;
		var R3Helper = {
			resize : function(){
				var height = document.body.offsetHeight ;
				document.getElementById('above').style.height = (height - 194 - 50)+"px" ;
			},
			showNotice:function (title , content , icon) {   
			    Notification.requestPermission(function (perm) {  
			        if (perm == "granted") {  
			            var notification = new Notification(title, {  
			                dir: "auto",  
			                lang: "zh",  
			                tag: "UCKeFu", 
			                icon:icon,
			                body: content
			            });  
			            setTimeout(function(){
			            	notification.close();
			            },5000);    
			        }  
			    });  
			}
		};
		var fineshed = false ;
		function resolved(){
			if(confirm("对话已结束，是否关闭浏览器窗口？")){
				fineshed = true ;
				window.close();
			}
		}
		function unresolved(){
			<#if aiConfig?? && aiConfig.selectskill?? && aiConfig.selectskill>
			var time = new Date().format("yyyy-MM-dd hh:mm:ss");
			var html = '<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">${inviteData.ainame!'小E'}</label><label class="time">'+time+'</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content"><div class="ukefu-askqs">${aiConfig.selectskillmsg!''}</div>';
			
			<#if skillList??>
			<#list skillList as skill>
			html = html + '<div class="ukefu-askqs-skill"><a href="/im/text/${appid!''}.html?skill=${skill.id!''}&ai=false">${skill.name!''}</a></div>' ;
			</#list>
			</#if>
			
			html = html + '</div></div></div>' ;
			output(html , 'chat-block');
			<#else>
			location.href = "/im/index.html?appid=${appid!''}&orgi=${orgi!''}&ai=false<#if client??>&client=${client!''}</#if><#if type??>&type=text</#if><#if skill??>&skill=${skill!''}</#if><#if agent??>&agent=${agent!''}</#if>&userid=${userid!''}&sessionid=${sessionid!''}&t=${.now?long}" ;
			</#if>
		}
		window.onbeforeunload = function(){
			if(fineshed == false){
				return "您确定断开对话？" ;
			}
		}
    </script>
    <!-- kindeditor -->
</head>
<body style="overflow:hidden;<#if inviteData.fullscreen?? && inviteData.fullscreen>max-width:100% !important;max-height:100% !important;</#if>" class="ukefu-point-text">
<div class="large ukefu-im-theme <#if type?? && type='text'>ukefu-theme-border-${inviteData.consult_dialog_color!''}</#if>">
    <div id="containter" class="clearfix">
    	<div id="header" class="theme${inviteData.consult_dialog_color!''}">
	   		<img src="<#if inviteData?? && inviteData.consult_dialog_logo??>/res/image.html?id=${inviteData.consult_dialog_logo?url}<#else>/images/logo.png</#if>" style="height:30px;padding:10px;">
	   		<#if !(inviteData?? && inviteData.consult_dialog_logo??)>
	   		<div style="position: absolute;left:165px;top:15px;">
	   			<img src="/im/img/xiaoe.png"/>
	   		</div>
	   		<div style="position: absolute;left:135px;top:15px;">
	             <img src="/im/img/e.png" style="width:22px;"/>
	        </div>
	        </#if>
	   		<div class="ukefu-func-tab">
		   		<ul>
		   			<#if models?? && models["xiaoe"]?? && models["xiaoe"] == true>
		   				<li class="cur"><a href="javascript:void(0)"><#if inviteData?? && inviteData.aitabtitle??>${inviteData.aitabtitle}<#else>智能客服</#if></a></li>
		   				<#if (!exchange?? || exchange == "true") && inviteData.hideagent == false>
		   				<li><a href="/im/index.html?appid=${appid!''}&orgi=${orgi!''}<#if aiid??>&aiid=${aiid}</#if>&ai=false<#if client??>&client=${client!''}</#if><#if type??>&type=text</#if><#if skill??>&skill=${skill!''}</#if><#if agent??>&agent=${agent!''}</#if><#if title??>&title=${title?url}</#if><#if url??>&url=${url?url}</#if><#if traceid??>&traceid=${traceid}</#if>&userid=${userid!''}&sessionid=${sessionid!''}<#if contacts?? && contacts.name??>&name=${contacts.name}</#if><#if contacts?? && contacts.phone??>&phone=${contacts.phone}</#if><#if contacts?? && contacts.email??>&email=${contacts.email}</#if><#if contacts?? && contacts.memo??>&memo=${contacts.memo}</#if>&t=${.now?long}<#if loginname??>&loginname=${loginname!''}</#if><#if token??>&token=${token!''}</#if><#if organ??>&organ=${organ!''}</#if><#if name??>&name=${name!''}</#if>"><#if inviteData?? && inviteData.agenttabtitle??>${inviteData.agenttabtitle}<#else>人工坐席</#if></a></li>
		   				</#if>
		   			<#else>
		   				<li class="cur"><a href="javascript:void(0)"><#if inviteData?? && inviteData.agenttabtitle??>${inviteData.agenttabtitle}<#else>人工坐席</#if></a></li>
		   			</#if>
		   		</ul>
	   		</div>
	    </div>
        <div class="content-left">
            <div class="chat-above" id="above">
            	<#if welcomeAd>
            	<div class="clearfix message  welcom"> 
            		<span id="welcome-message">
            			<#if welcomeAd.adtype =="image">
						<a href='${welcomeAd.url!''}' title='${welcomeAd.tiptext!''}' target='_blank'><img src='${welcomeAd.imgurl!''}' style='max-width:420px;max-height:178px;margin:0px;vertical-align: middle;'/></a>
						<#else>
						<div style='padding:0px 5px 10px 5px;border-bottom:1px solid #dedede;'><a href='${welcomeAd.url!''}' title='${welcomeAd.tiptext!''}' target='_blank' id='point_ad_text'>${(welcomeAd.content!'')?no_esc}</a></div>
						</#if>
            		</span>
            	</div>
            	</#if>
            	<div class="clearfix message  welcome"> <span id="welcome-message">
            		<#if aiConfig?? && aiConfig.welcomemsg??>
            			${aiConfig.welcomemsg?no_esc}
            		<#else>
            			<#if inviteData.aimsg?? && inviteData.aimsg!=''>${inviteData.aimsg?no_esc}<#else>${(inviteData.dialog_message!'欢迎您来咨询！')?no_esc}</#if></span>
            		</#if>
            	</div>
				<#if chatMessageList?? && chatMessageList.content??>
					<#list chatMessageList.content?reverse as chatMessage>
						<#if chatMessage.msgtype == "status" && chatMessage.message == "end">
							<div class="clearfix chat-block connect-end">
								<span class="connect-end-message">${chatMessage.updatetime?number_to_datetime}，用户“<#if chatMessage?? && chatMessage.username??>${chatMessage.username!''}</#if>”已经离开</span>
							</div>
						<#else>
							<#if chatMessage.userid?? && userid?? && chatMessage.calltype?? && chatMessage.calltype = "in">
								<div class="clearfix chat-block">
									<div class="chat-right"> 
										<img class="user-img" src="/im/img/user.png" alt="">
										<div class="chat-message">
											<label class="time">${chatMessage.createtime!''}</label>
											<label class="user">${chatMessage.username!''}</label> 
										</div>
										<div class="chatting-right">
											<i class="arrow arrow${inviteData.consult_dialog_color!''}"></i>
											<div class="chat-content theme${inviteData.consult_dialog_color!''}"><#include "/apps/im/media/message.html"></div>
										</div>
									</div>
								</div>
							<#else>
								<div class="clearfix chat-block">
									<div class="chat-left"> 
										<img class="user-img" src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt="">
										<div class="chat-message">
											<label class="user">${chatMessage.username!inviteData.ainame!'小E'}</label> 
											<label class="time">${chatMessage.createtime!''}</label>										
										</div>
										<div class="chatting-left">
											<i class="arrow"></i>
											<div class="chat-content"><#include "/apps/im/media/message.html"></div>
										</div>
									</div>
								</div>
							</#if>
						</#if>
					</#list>
				</#if>
			</div>
            <div class="chat-bottom" id="bottom">
				<textarea id="message" name="content" style="visibility:hidden;"></textarea>
				<div class="btn-push clearfix">
					<div style="float:left;height:34px;line-height:34px;margin: 10px 20px 10px 5px;" id="surplus">0/200</div>
					<button type="button" class="send-btn active special  clearfix" id="sent" onclick="sendMessage()">
						发送
					</button>
				</div>
			</div>
        </div>
        <div class="content-rig">
            <div class="content-list" style="padding-top:50px;height: calc(100% - 50px);">
            	<div class="content-head">
	                <div style="padding-top:0px;padding-left:5px;    position: relative;">
	                	<div style="margin-left:5px;margin-top:5px;position: absolute;;">
	                		<img src="/im/img/ask.png" style="width:22px;"/>
	                	</div>
	                	<div style="position: absolute;left:38px;top:7px;">热门问题？</div>
	                </div>
	            </div>
	            
	            <ul style="overflow-y: auto;height: calc(100% - 50px);overflow-x:hidden;">
                	<#if topicTypeList?? && topicTypeList?size gt 0>
                	<#list topicTypeList as topicType>
                	<li class="ukefu-xiaoe-topictype">
						<h2 class="ukefu-xiaoe-topictype-title">${topicType.name!''}</h2>
						<ul>
		                	<#if topicList??>
		                	<#list topicList as topic>
		                	<#if topic.cate?? && topicType.id == topic.cate>
		                	<li class="ukefu-ask-item">
								<a href="javascript:void(0);" data-id="1" onclick="sendMessageTextWithID(decodeURIComponent('${(topic.title!'')?url}') , '${topic.id!''}');">
									<span>${topic.title!''}</span>
									<i class="iconfont right-icon icon-enter"></i>
								</a>
							</li>
							</#if>
							</#list>
							</#if>
		                </ul>
					</li>
					</#list>
					<#else>
					<li class="ukefu-xiaoe-topictype">
						<h2 class="ukefu-xiaoe-topictype-title">默认分类</h2>
						<ul>
		                	<#if topicList??>
		                	<#list topicList as topic>
		                	<#if !(topic.cate??) || topic.cate == "default">
		                	<li class="ukefu-ask-item">
								<a href="javascript:void(0);" data-id="1" onclick="sendMessageTextWithID('${topic.title!''}' , '${topic.id!''}');">
									<span>${topic.title!''}</span>
									<i class="iconfont right-icon icon-enter"></i>
								</a>
							</li>
							</#if>
							</#list>
							</#if>
		                </ul>
					</li>
					</#if>
                </ul>
            </div>
        </div>
    </div>
    <div id="footer"></div>
</div>
<#if (sessionConfig?? && sessionConfig.satisfaction?? && sessionConfig.satisfaction) || (snsaccount?? && snsaccount.satisfaction?? && snsaccount.satisfaction)>
<!--调查问卷弹框-->
<div class="diaShade" id="diaShade" style="display: none"></div>
<div class="dialogWrap" id="dialogWrap" style="display: none;">
    <div class="dialogCon">
        <form id="commentContent" onSubmit="return submitForm(this)">
        	<input type="hidden" name="id" id="agentserviceid" name="agentserviceid">
            <h2 class="diaHeader clearfix">
                <span>评价</span>
                <hr>
            </h2>
            <p class="title">您是否对此次服务满意?</p>
            <!--评价-->
           <p style="margin-top:20px;">
                <span style="float:left;">评价：</span>
                <span style="position: relative;top: 0px;left: 13px;">
                <#assign defaultvalue = "">
                <#if commentList??>
                <#list commentList as comment>
		        <input type="radio" name="satislevel" value="${comment.code!''}" <#if comment_index == 0>checked="checked"</#if> id="dic_${comment.id!''}" onclick="document.getElementById('satislevel_input').value = this.value">
		        <label for="dic_${comment.id!''}" class="radio">${comment.name!''}</label>
                <#if defaultvalue == "">
                <#assign defaultvalue = comment.code>
                </#if>
                </#list>
                </#if>
                <input type="hidden" id="satislevel_input" name="t" value="${defaultvalue}">
                </span>
            </p>
            <!--描述-->
            <p style="margin-top:20px;">
                <span style="float:left;">意见：</span>
                <span style="position: relative;top: 0px;left: 10px;">
                	<input type="hidden" id="comment_input" name="t">
                	<#if commentItemList??>
                	<#list commentItemList as item>
                	<div style="margin-left:55px;margin-bottom:20px;">
                		<input type="radio" name="comment" id="item_${item.id!''}" value="${item.id!''}" onclick="document.getElementById('comment_input').value = this.value">
                		<label for="item_${item.id!''}" class="radio">
                			${item.name!''}
                		</label>
                	</div>
                	</#list>
                	</#if>
                </span>
            </p>
            <!--按钮-->
            <p class="submitBtnWrap" style="text-align:center;">
				<input type="submit" class="btn submitBtn" id="submitBtn" value="提 交">
            </p>
        </form>
    </div>
</div>
</#if>
<script>
	var service_end = false ;
	R3Helper.resize();
    // 调查问卷
    var diaShade=document.getElementById('diaShade');
    var dialogWrap=document.getElementById('dialogWrap');
    function popup(para) {
        diaShade.style.display=para;
        dialogWrap.style.display=para;
    }
    <#if !welcomeAd>
    document.getElementById('above').scrollTop = document.getElementById('above').scrollHeight  ;	//滚动到 对话内容的 底部
    </#if>
    // 参数连接
    var timer = setInterval(function(){
			if(socket!=null && socket.connected == true){
				socket.emit("ping");
			}
		},5000);
	var hostname = location.hostname ;
    var socket = null;
    var webimWoker = {
    		init:function(url , staticagent){
    			socket = io.connect(url , options);
    		    socket.on('connect',function(){
    		        //service.sendRequestMessage(); 
    				//output('<span id="connect-message">'+ new Date().format("yyyy-MM-dd hh:mm:ss") + ' 开始沟通' +'</span>' , 'message connect-message');
    				socket.emit('new', {
			    		<#if contacts?? && contacts.name??>
						name : "${contacts.name!''}",
						phone:"${contacts.phone!''}",
						email:"${contacts.email}",
						memo:"${contacts.memo!''}",
						nickname:"${contacts.name}",
						<#else>
			    		nickname:"${username}",
						</#if>
						orgi:"${inviteData.orgi!''}",
						appid : "${appid!''}",
						aiid : "${aiid!''}",
						user:"${creater!''}",
						session:"${sessionid!''}",
						mobile:"${mobile!'0'}",
						osname:"${(osname!'')?url}",
						staticagent:staticagent,
						browser:"${(browser!'')?url}"
						<#if skill??>,skill:"${skill}"</#if>
						<#if agent??>,agent:"${agent}"</#if>
						<#if title??>,title:"${title?url}"</#if>
						<#if traceid??>,url:"${url?url}"</#if>
						<#if traceid??>,traceid:"${traceid}"</#if>
					});
    		    	service_end = false ;
    		        fineshed = false ;
    		    })
    		    socket.on("agentstatus",function(data){
    		    	var message = "${inviteData.aisuccesstip!''}" ;
    		    	if(message != "" && agent == false){
    		    		document.getElementById('connect-message').innerHTML = message;
    		    	}else{
    		       		document.getElementById('connect-message').innerHTML = data.message;
    		    	}
    		    	editor.readonly(false);
    		    })
    		    socket.on("status",function(data){
    		    	var message = "${inviteData.aisuccesstip!''}" ;
    		    	if(message == "" || agent == true){
    		       		message = data.message ;
    		    	}
    		    	<#if welcomeAd>
    				output('<span id="connect-message" <#if inviteData.tipmsgbgcolor?? && inviteData.tipmsgbgcolor!=''>class="theme${inviteData.tipmsgbgcolor!''}"</#if>>'+message+'</span>' , 'message connect-message' , false);    
    				<#else>
    		    	if(data.message!="" && staticagent == false){
    					output('<span id="connect-message" <#if inviteData.tipmsgbgcolor?? && inviteData.tipmsgbgcolor!=''>class="theme${inviteData.tipmsgbgcolor!''}"</#if>>'+message+'</span>' , 'message connect-message');    
    		    	}
    				</#if>     
    				 
    				if(data.messageType == "end"){
    					service_end = true ;
    					editor.readonly();
    					if(staticagent == true){
        		        	output('<span id="connect-message" <#if inviteData.tipmsgbgcolor?? && inviteData.tipmsgbgcolor!=''>class="theme${inviteData.tipmsgbgcolor!''}"</#if>>对话已经结束，请关闭浏览器</span>' , 'message connect-message');
    						staticagent = false ;
        		    	}
    				}
    				<#if (sessionConfig?? && sessionConfig.satisfaction?? && sessionConfig.satisfaction) || (snsaccount?? && snsaccount.satisfaction?? && snsaccount.satisfaction)>
    				if(data.messageType == "invit" || data.messageType == "end"){
    					<#if (sessionConfig?? && sessionConfig.satisfaction?? && sessionConfig.satisfaction) || (snsaccount?? && snsaccount.satisfaction?? && snsaccount.satisfaction)>
    					if(invite == false){
    						document.getElementById("diaShade").style.display = "block" ;
    						document.getElementById("dialogWrap").style.display = "block" ;
    						invite = true ;
    					}
    					</#if>
    				}
    				</#if>
    				if(document.getElementById("agentserviceid")){
    					document.getElementById("agentserviceid").value = data.agentserviceid ;
    				}
    		    })
    		    socket.on('message', function(data) {
    		        var chat=document.getElementsByClassName('chatting-left').innerText;
    		        chat = data.message;
    		        if(data.quickagent == true){
    		        	//转人工
    					callback = "quickagent(false)";
    					sendDisconnect(false);
    		        }else{
	    		        if(data.messageType == "image"){
	    		        	chat = "<img src='"+data.message+"' class='ukefu-media-image'>" ;
	    		        }else if(data.messageType == "voice"){
	    		        	chat = template($('#message_tpl').html(), {data: data}) ;
	    		        }
	    		        var text = '<ul class="info-list">' ;
	    		        if(data.suggest!=null){
	    		        	for(inx =0 ; inx < data.suggest.length ; inx++){
	    		        		var item = data.suggest[inx] ;
	    		        		text = text + '<li class="ukefu-suggest-item"><a href="javascript:void(0)" class="suggestitem" onclick="sendMessageTextWithID(\''+item.title.replace(/'/g,"")+'\' , \''+item.id+'\')">'+item.title+'</a></li>' ;
	    		        	}
	    		        	text = text + "</ul>";
	    		        	chat = chat + text ;
	    		        }
	    				if(data.calltype == "in"){
	    					output('<div class="chat-right"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label class="time">'+data.createtime+'</label><label  class="user">'+data.nickName+'</label> </div><div class="chatting-right"><i class="arrow arrow${inviteData.consult_dialog_color!''}"></i><div class="chat-content theme${inviteData.consult_dialog_color!''}">'+chat+'</div></div>' , "chat-block");
	    				}else if(data.calltype == "out"){
	    					/***延迟1秒执行，不然太快****/
	    					
	    					setTimeout(function(){
	    						var ext_message = "" ;
	    						//开启知识点评价功能
	    						<#if aiConfig?? && aiConfig.topicuseful>
	    						if(data.topic == true){
	    							ext_message = "<div class='ukefu-ai-tip' id='ukefu_ai_msg_"+data.id+"'><span><#if aiConfig.topicusefulmsg?? && aiConfig.topicusefulmsg!=''>${aiConfig.topicusefulmsg!''}<#else>此条知识是否解决了问题？</#if></span><span><span class='ukefu-ai-btn ukefu-ai-btn-ok' data-id='"+data.id+"'><i class='iconfont'>&#xe640;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulok?? && aiConfig.topicusefulok!=''>${aiConfig.topicusefulok}<#else>已解决</#if></span><span class='ukefu-ai-btn ukefu-ai-btn-no'  data-id='"+data.id+"'><i class='iconfont'>&#xe629;</i>&nbsp;&nbsp;<#if aiConfig.topicusefulno?? && aiConfig.topicusefulno!=''>${aiConfig.topicusefulno}<#else>未解决</#if></span></span></div>" ;
	    						}
	    						</#if>
	    						<#if aiConfig?? && aiConfig.sysmsgtransagent>
	    						if(data.topic == false && data.matchtype == "no"){
	    							ext_message = "<div class='ukefu-ai-tip' id='ukefu_ai_msg_"+data.id+"'><span class='ukefu-ai-btn-sysmsgtrans'><#if aiConfig.sysmsgtransagentmsg?? && aiConfig.sysmsgtransagentmsg!=''>${aiConfig.sysmsgtransagentmsg!''}</#if></span><#if aiConfig?? && aiConfig.quickagent?? && aiConfig.quickagent == true><span class='ukefu-ai-btn ukefu-ai-quickagent'><i class='iconfont'>&#xe698;</i>&nbsp;&nbsp;${aiConfig.quickagentmsg!'立即转人工坐席'}</span></#if></span></div>" ;
	    						}
	    						</#if>
	    						
		    					
	    						if(data.staticagent == true && <#if inviteData?? && inviteData.staticagent == true>true<#else>false</#if>){
	    							//转人工
	    							staticagent = true ;
	    							callback = "quickagent(true)";
	    							sendDisconnect(true);
	    						}else{
	    							output('<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">'+"${inviteData.ainame!'小E'}"+'</label><label class="time">'+data.createtime+'</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">'+chat + ext_message+'</div></div>' , "chat-block");
	    						}
	    						
	    						
	    						if(tipuser && tipuser == 'true'){
	    							R3Helper.showNotice(tipusertitle , data.message , tipusericon);
	    						}
	    						R3Ajax.audioplayer('audioplane', newmessage, false); // 播放
	    					} , 500);
	    				}
    		        }
    		    });
    		    
    		    socket.on('new', function(data) {
    		    	alert(data.agentserviceid);
    		    }); 
    		    
    		    socket.on('disconnect',function() {
    		    	var time = new Date().format("yyyy-MM-dd hh:mm:ss");
    		    	<#if aiConfig?? && aiConfig.askqs && aiConfig.asktipmsg?? && aiConfig.asktipmsg!="">
    		    	if(staticagent == false || callback == null){
    		    		output('<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.aiicon??>/res/image.html?id=${inviteData.aiicon?url}<#elseif inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">${inviteData.ainame!'小E'}</label><label class="time">'+time+'</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content"><div class="ukefu-askqs">${aiConfig.asktipmsg!''}</div><span class="ukefu-askqs-resolved"><a href="javascript:void(0)" onclick="return resolved();">${aiConfig.resolved!"已解决"}</a></span><span class="ukefu-askqs-unresolved"><a href="javascript:void(0)" onclick="return unresolved();">${aiConfig.unresolved!"未解决"}</a></div></div></div>' , 'chat-block');
    		    	}
    		    	<#else>
    		    	if(staticagent == false){
    		        	output('<span id="connect-message" <#if inviteData.tipmsgbgcolor?? && inviteData.tipmsgbgcolor!=''>class="theme${inviteData.tipmsgbgcolor!''}"</#if>>对话已经结束，请关闭浏览器</span>' , 'message connect-message');
    		    	}
    		        </#if>
    		        service_end = true ;
    		        fineshed = true ;
    		        editor.readonly();
    				$('.ukefu-ai-quickagent').remove();
    				webimWoker.off();
    				if(callback!=null){
    		    		setTimeout(function(){eval(callback);callback = null ; }, 500);
    		    	}
    		    });
    		},
    		off:function(){
    			webimWoker.delevent('connect');
    			webimWoker.delevent('agentstatus');
    			webimWoker.delevent('message');
    			webimWoker.delevent('disconnect');
    		},
    		delevent:function(name){
    			var event = socket.listeners(name) ;
    			if(event.length > 1){
    				for(i = 0 ; i<event.length ; i++){
	    				socket.off(name , event[i]);
    				}
    			}else{
    				socket.off(name , event[0]);
    			}
    		}
    }
    function sendDisconnect(agent){
    	if(socket!=null){
    		socket.emit('end', {
				orgi:"${inviteData.orgi!''}",
				appid : "${appid!''}",
				aiid : "${aiid!''}",
				user:"${creater!''}",
				staticagent:staticagent
			});
    		//无感知转人工
    		staticagent = agent ;
			socket.disconnect();
		}
    }
    function sendMessage() {
		editor.sync();
		var count = editor.count("text");
		if(count>0 && service_end == false){
	        var message = document.getElementById('message').value;
	        sendMessageText(message);
		}else if(service_end == true){
			alert("服务器已断开和您的对话");	
		}
		editor.html('');
    }
    function sendMessageText(message){
    	if(message!= ""){ 
    		sendMessageTextWithID(message , null) ;
		}
    }
    function sendMessageTextWithID(message , id){
    	if(message!= ""){ 
			socket.emit('message', {
					appid : "${appid!''}",
					username:"${username!''}",
					channel:"webim",
					type:"message" ,
					contextid:"${sessionid!''}",
					orgi:"${orgi!''}",
					mediaid:id,
					message :  message
			});
		}
    }
    function output(message , clazz , scroll) {
		if(clazz == "message connect-message"){
			var messages = document.getElementsByClassName("connect-message") ;
			for(inx =0 ; inx < messages.length ; ){
				document.getElementById('above').removeChild(messages[inx]) ;
				inx++ ;
			}			
		}
        var element = ("<div class='clearfix "+clazz+"'>" +" " + message + "</div>");
        $('#above').append(element);
        if(scroll == null || scroll == true){
			document.getElementById('above').scrollTop = document.getElementById('above').scrollHeight  ;
		}
		
    }
	function update(id , message) {
        document.getElementById(id).innerHTML= message;
    }
    
    var message={
        // text:data.message,
        // picture:function(){

        // }
        // file:function(){

        // }
        // lang:function(){

        // }
        // goods:function(){

        // }
        // POI:function(){

        // }

    }
    // 回车事件
    document.onkeyup=function(e){
        if(!e) e=window.event;
        if((e.keyCode||e.which)==13){
            document.getElementById('sent').click();
        }
    }
	window.onresize = function(){
		R3Helper.resize();		
	};
	$(document).ready(function(){
		$(document).on('click','.ukefu-ai-btn-ok', function ( e ) {
			$('#ukefu_ai_msg_'+$(this).data("id")).empty().html("<span class='ukefu-ai-btn-ok-tip'><i class='iconfont'>&#xe61b;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span>") ;
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/message/useful.json?id="+$(this).data("id"),
	             dataType: "json",
	             success: function(data){
	             	
	             }
	         });
		});
		$(document).on('click','.ukefu-ai-btn-no', function ( e ) {
			var obj = $(this) ;
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/message/unuseful.json?id="+$(this).data("id"),
	             dataType: "json",
	             success: function(data){
	             	
	             }
	         });
			$.ajax({
	             type: "GET",
	             url: "/rest/webim/agent.json?orgi=${orgi}",
	             dataType: "json",
	             success: function(data){
	             	if(data.data.agents > 0){
	             		$('#ukefu_ai_msg_'+$(obj).data("id")).empty().html("<span class='ukefu-ai-btn-no-tip'><i class='iconfont'>&#xe62d;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span><#if aiConfig?? && aiConfig.quickagent?? && aiConfig.quickagent == true><span class='ukefu-ai-btn ukefu-ai-quickagent'><i class='iconfont'>&#xe698;</i>&nbsp;&nbsp;${aiConfig.quickagentmsg!'立即转人工坐席'}</span></#if>") ;	             		
	             	}else{
	             		$('#ukefu_ai_msg_'+$(obj).data("id")).empty().html("<span class='ukefu-ai-btn-no-tip'><i class='iconfont'>&#xe62d;</i>&nbsp;&nbsp;${aiConfig.topicusefultip!''}</span><span><#if aiConfig?? && aiConfig.noagentmsg?? && aiConfig.noagentmsg != ''>${aiConfig.noagentmsg}<#else>无人工坐席在线</#if></span>") ;
	             	}
	             }
	         });
			
		});
		$(document).on('click','.ukefu-ai-quickagent', function ( e ) {
			//转人工
			callback = "quickagent(false)";
			sendDisconnect(false);
		});
		webimWoker.init('${schema!'http'}://'+hostname+':${port}/im/ai' , false);
	});
	function submitForm(form){
		$.post("/im/satis.html?orgi=${orgi!''}&"+"id="+form.id.value+"&satislevel="+document.getElementById("satislevel_input").value +"&satiscomment="+encodeURIComponent(document.getElementById("comment_input").value) , function(data) {
			document.getElementById("diaShade").style.display = "none" ;
			document.getElementById("dialogWrap").style.display = "none" ;
			alert("服务评价已提及，请关闭浏览器！");
		});
		return false ;
	}
	function quickagent(staticagent){
		webimWoker.init('${schema!'http'}://'+hostname+':${port}/im/user' , staticagent) ;
		editor.readonly(false);
		agent = true ;
		callback = null ;
		staticagent = false ;
	}
	<#if inviteData?? && inviteData.enablevoice?? && inviteData.enablevoice == true>
	UCKeFuVoice.init("webim");
	</#if>
</script>
<script id="message_tpl" type="text/html">
	<p class="weixinAudio" id="voice_media_<%:=data.id%>" style="<% if(data.duration > 30) {%>width:300px;<% }else{ %>width:<%:=50+data.duration* 10%>px;<%}%>">
		<audio src="<%:=data.message%>" id="media" width="1" height="1" preload></audio>
		<span id="audio_area" class="db audio_area">
			<span class="audio_wrp db">
				<span class="audio_play_area">
					<i class="icon_audio_default"></i>
					<i class="icon_audio_playing"></i>
				</span>
				<span class="audio_length tips_global"><%:=data.duration %>秒</span>
				<span id="audio_progress" class="progress_bar" style="width: 0%;"></span>
			</span>
		</span>
	</p>
	<script type='text/javascript'>
		$('#voice_media_<%:=data.id%>').weixinAudio({
			autoplay:false
		});
	<\/script>
</script>
</body>
</html>